﻿using System.Linq;
using System.Collections.Generic;
using System.Text;
using System;
using Crawler.IRepositories;
using Crawler.Model.SystemDefault;
using Crawler.IRepositories.SystemDefault;
using Crawler.Framework.Repositories;
using Microsoft.EntityFrameworkCore;
using SqlSugar;

namespace Crawler.Framework.Repositories.SystemDefault
{
    public class HttpConfigRepository : Repository<ProxyIPModel>, IHttpConfigRepository
    {
        private Random random;
        private static List<string> _userAgentList;

        static HttpConfigRepository()
        {
            _userAgentList = new List<string>
            {
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
                "Opera/9.80 (Windows NT 6.1; U; zh-cn) Presto/2.9.168 Version/11.50"
            };
        }

        public HttpConfigRepository(SqlSugarClient context) : base(context)
        {
            this.random = new Random();
        }

        public string GetProxyIP()
        {
            // 随机返回高匿代理 地址
            var set = this.Find(ip=>ip.AddressStatus== AddressStatus.Available);
            if (set.Count() > 0)
            {
                var index = random.Next(0, set.Count() - 1);
                return set.Skip(index).Take(1).Select(ip => string.Format("{0}:{1}", ip.IPAddress.Trim(), ip.Port.Trim())).FirstOrDefault();
            }
            return null;
        }

        public string GetUserAgent()
        {
            // 随机获取 agent信息
            return _userAgentList[this.random.Next(0, _userAgentList.Count-1)];
        }
    }
}
